
package com.xsl.controller;
import com.xsl.dao.ChatHistoryDao;
import com.xsl.pojo.vo.MessageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import java.util.List;


@RestController
@RequestMapping("/ai")
@Slf4j
public class ChatController {

    @Autowired
    private ChatClient chatClient;

    @Autowired
    private ChatHistoryDao chatHistoryDao;

    @Autowired
    private ChatMemory chatMemory;

    //定义一个方法，用于处理前端方法的请求
    @RequestMapping(value = "/chat",produces = "text/html;charset=utf-8")
    public Flux<String> chat(@RequestParam String prompt,String chatId){
        log.info("接收到用户的输入:{}",prompt);
        log.info("接收到用户的chatID:{}",chatId);
        chatHistoryDao.sava(prompt,chatId);

        //静态的调用
//        return chatClient.prompt().user(prompt).call().content();
        return chatClient.prompt()
                .advisors(advisorSpec -> advisorSpec.param(ChatMemory.CONVERSATION_ID,chatId))
                .user(prompt).stream().content();//动态的调用


    }
    @GetMapping("/history/{type}")
    public List<String> chatHistory(@PathVariable String type){
        log.info("type:{}",type);
        return chatHistoryDao.fetchChatHistory(type);
    }
    @GetMapping("/history/{type}/{chatId}")
    public List getChatHistory(@PathVariable String type, @PathVariable String chatId) {
        log.info("type:{},chatId{}",type,chatId);
        List<Message> messageList = chatMemory.get(chatId);
        /**
         * 1.遍历message
         * 2.将集合中的Message对象拿到，然后封装到MessageVO中，然后放到List中返回
         * 3.再将List返回给前端
         */
        return messageList.stream().map(MessageVO::new).toList();
    }

}